package com.ruoyi.iot;


import com.ruoyi.iot.handler.MqttMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

/**
 * 接收mqtt消息入口
 */
@Slf4j
@Component
public class DefaultMessageHandler implements MessageHandler{


    @Resource
    MqttMessageHandlerFactory mqttMessageHandlerFactory;

    /**
     *  接收mqtt消息,alink协议 :/sys/${productKey}/${deviceKey}/thing/event/${channelKey}/post
     */
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
      try {

        String topic = message.getHeaders().get("mqtt_receivedTopic", String.class);
        log.info("topic: {}",topic);
        log.info("message：{}",message.getPayload().toString());

        // 从mqtt topic中解析出消息类型
        String messageType = "";

        MqttMessageHandler mqttMessageHandler = mqttMessageHandlerFactory.getMessageHandler(messageType);
        mqttMessageHandler.process(topic,(String) message.getPayload());
      } catch (Exception e) {
        log.error("处理mqtt消息失败",e);
      }

    }
    
}
